package com.bite.book.interceptor;

import com.bite.book.constant.Constants;
import com.bite.book.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //true --放行  false--拦截
        log.info("登录拦截...");
        HttpSession session = request.getSession(false);
        if (session==null || session.getAttribute(Constants.SESSION_USER_KEY)==null ||
                !StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_USER_KEY))){
            //用户未登录
            log.error("用户未登录, 进行拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            //此处我只是举例
            Result result = Result.unlogin();
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            response.setContentType("application/json;charset=utf-8");
            return false;
        }
        log.info("用户登录校验通过..");
        return true;
    }


//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("执行postHandle.....");
//    }

//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("执行afterCompletion");
//    }
}
